#!/usr/bin/env python3
"""Generate a .profile, outputting to stdout.

Handle setting PATH, MANPATH, CPPFLAGS, LDFLAGS, and aliases.

"""
import contextlib
import logging
import os


def cleanup_paths(*paths):
    return [os.path.realpath(os.path.expanduser(path)) for path in paths]


USR = cleanup_paths(
        '~/.slash/_',
        '~/.local',
        )
BIN_ONLY = cleanup_paths('/Developer/usr/bin', '~/Dev/depot_tools',
                            # ~/.gem/ruby/1.8/bin,
                        )
ALIASES = cleanup_paths(
        '~/.slash/_/svnmerge/svnmerge.py',
        )
JARS = cleanup_paths(
        '~/.slash/_/jython2.5',
        )


def print_section(title):
    print(' {0} '.format(title).center(40, '#'))


def set_usr(var, *dirs, suffix=None):
    """Set an environment variable based on a list of directories and a
    prefix."""
    if suffix:
        dirs = (os.path.join(directory, suffix) for directory in dirs)
    paths = []
    for x in dirs:
        if not os.path.exists(x):
            logging.warning('{0} does not exist.'.format(x))
            continue
        paths.append(x)
    if not paths:
        return None
    print('{0}={1}'.format(var, ':'.join(paths)))
    return var


@contextlib.contextmanager
def create_usr(var):
    print_section(var)
    print('ORIGINAL_{0}=${0}'.format(var))
    yield
    print('{0}=${0}:$ORIGINAL_{0}'.format(var))
    print('export {0}'.format(var))
    print()


def create_flags(var, flag, suffix, *dirs):
    print_section(var)
    maybe_paths = (os.path.join(directory, suffix) for directory in dirs)
    paths = []
    for x in maybe_paths:
        if not os.path.exists(x):
            logging.warning('{0} does not exist.'.format(x))
            continue
        paths.append(x)
    flags = ('-{0}{1}'.format(flag, path) for path in paths)
    print('{0}="${0} {1}"'.format(var, ' '.join(flags)))
    print('export {0}'.format(var))
    print()


def create_classpath(*dirs):
    print_section("CLASSPATH")
    found =['.']
    for x in dirs:
        if not os.path.exists(x):
            logging.warning("{0} does not exist.".format(x))
            continue
        contents = os.listdir(x)
        for thing in contents:
            if thing.endswith('.jar'):
                found.append(os.path.join(x, thing))
    print("export CLASSPATH={0}".format(':'.join(found)))
    print()


def create_aliases(*aliases):
    print_section('Aliases')
    for alias in aliases:
        if not os.path.exists(alias):
            logging.warning('{0} does not exist.'.format(alias))
            continue
        program = os.path.basename(alias)
        print('alias {0}={1}'.format(program, alias))
    print()

print("# AUTO-GENERATED for .zshenv")
with create_usr('PATH'):
    created = set()
    created.add(set_usr('S_PATH', *USR, suffix='sbin'))
    created.add(set_usr('PATH', *USR, suffix='bin'))
    created.add(set_usr('BIN_ONLY_PATH', *BIN_ONLY))
    try:
        created.remove(None)
    except KeyError:
        pass
    print('PATH=$'+':$'.join(created))

with create_usr('MANPATH'):
    paths = USR[:] + [os.path.join(x, 'share') for x in USR]
    set_usr('MANPATH', *paths, suffix='man')

create_flags('CPPFLAGS', 'I', 'include', *USR)
create_flags('LDFLAGS', 'L', 'lib', *USR)

create_classpath(*JARS)

create_aliases(*ALIASES)
